#!/usr/bin/env bash

export FLATHUB_CACHE="$HOME/.cache/linglong-pica-flathub"
export LL_PICA_FLATPAK_PATH="$(realpath --no-symlinks "$(dirname "${BASH_SOURCE[0]}")")"
export LL_PICA_FLATPAK_CONFIG_FILE="$HOME/.pica/ll-pica-flatpak-config.json"
export LL_PICA_FLATPAK_REFS_FILE="$HOME/.pica/ll-pica-flatpak-refs.txt" # 存放 flathub 仓库 refs 的文件

mkdir -p "$HOME"/.pica

if [[ ! -e $LL_PICA_FLATPAK_CONFIG_FILE ]];
then
    tee "$LL_PICA_FLATPAK_CONFIG_FILE" <<EOF
{
    "flathub": {
        "url": "https://dl.flathub.org/repo/"
    }
}

EOF
fi

if [[ ! -e $LL_PICA_FLATPAK_REFS_FILE ]];
then
    "${LL_PICA_FLATPAK_PATH}/ll-pica-flatpak-utils" generate_ref_cache
fi

function main() {
    COMMAND=$1
    APPID=$2

    ARCH=$(uname -m)
    LONG_OPTS="base:,base-version:,version:,build,layer,help"
    SHORT_OPTS="h"

    if [[ $# != 0 ]];
    then
        GETOPT_ARGS=$(getopt -o $SHORT_OPTS -l $LONG_OPTS -- "$@")
        eval set -- "$GETOPT_ARGS"

        # 提取长选项参数
        while true
        do
            case "$1" in
                --base) test -z "$2" || BASE="$2"; shift 2;;
                --base-version) test -z "$2" || BASE_VERSION="$2"; shift 2;;
                # # 转换为玲珑的版本，规则是按'.'和'-'分割取前三位，不足三位补0，再末尾补充输入的打包版本号，如 5.15-23.08 生成 5.15.23.0
                --version) test -z "$2" || VERSION="$(echo "$2" | grep -oE '[0-9]+' | awk '{a[NR]=$0} END {for(i=1;i<=4;i++) printf "%s%s", (i>1?".":""), (i in a ? a[i] : 0)}')"; shift 2;;
                --build) test -z "$2" || BUILD=true; shift 1;;
                --layer) test -z "$2" || LAYER=true; shift 1;;
                -h|--help) test -z "$2" || "${LL_PICA_FLATPAK_PATH}/ll-pica-flatpak-utils" help; shift 1; exit 0;;
                --) shift; break;;
                *) echo echo "Programming error $1 , $2"; exit 1;;
            esac
        done
    fi

    export BASE
    export BASE_VERSION

    if [[ -z $VERSION ]];
    then
        VERSION="1.0.0.0"
    fi

    if [[ -z $BUILD ]];
    then
        BUILD=false
    fi

    if [[ -z $LAYER ]];
    then
        LAYER=false
    fi

    export REF="flathub:app/$APPID/$ARCH/stable"

    echo "init flathub cache"
    ostree init --repo="$FLATHUB_CACHE" --mode bare-user-only

    FLATHUB_URL=$(jq -r ".flathub.url" "$LL_PICA_FLATPAK_CONFIG_FILE")
    ostree --repo="$FLATHUB_CACHE" remote add --if-not-exists --no-sign-verify flathub "$FLATHUB_URL"

    case "${COMMAND}" in
        convert)
            "${LL_PICA_FLATPAK_PATH}/ll-pica-flatpak-convert" "$APPID" "$VERSION" "$BUILD" "$LAYER"
            ;;
        help | --help | -h)
            exit 0
            ;;
        *)
            printf >&2 "Error: invalid command\n"
            exit 1
    esac
}

main "$@"
